package base.thread.synchronizer;

import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.Exchanger;

public class ExchangeDemo {

	@SuppressWarnings("rawtypes")
	private static Exchanger ex = new Exchanger();

	public static void main(String[] args) {
		ExchangeDemo demo = new ExchangeDemo();
		new Thread(demo.new DataProducer()).start();
		new Thread(demo.new DataConsumer()).start();
	}

	class DataProducer implements Runnable {
		private List<Date> list = new ArrayList<Date>();
		private List<String> recive = new ArrayList<String>();

		@SuppressWarnings("unchecked")
		public void run() {
			for (int i = 0; i < 5; i++) {
				System.out.println("生产一个数据，耗时1秒");
				list.add(new Date());
				try {
					Thread.sleep(1000);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			try {
				recive = (List<String>) ex.exchange(list);
				Thread.sleep(1);
			} catch (Exception e) {
				e.printStackTrace();
			}

			for (Iterator<String> iterator = recive.iterator(); iterator
					.hasNext();) {
				System.out.println("Producer:" + iterator.next());
			}
		}
	}

	class DataConsumer implements Runnable {
		private List<String> list = new ArrayList<String>();
		private List<Date> reci = new ArrayList<Date>();

		@SuppressWarnings("unchecked")
		public void run() {
			for (int i = 0; i < 5; i++) {
				list.add("这是一个收条");
			}
			try {
				reci = (List<Date>) ex.exchange(list);
			} catch (Exception e) {
				e.printStackTrace();
			}

			for (Iterator<Date> iterator = reci.iterator(); iterator.hasNext();) {
				Date d = (Date) iterator.next();
				System.out.println("Consumer:" + d);
			}
		}
	}
}
